/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JPanel;

/**
 *
 * @author Zhilin
 */
public class DatePickerEventListener implements ActionListener{
    
    @Override
    public void actionPerformed(ActionEvent e) {
        JComboBox problem = (JComboBox)(e.getSource());
        JPanel parent = (JPanel)problem.getParent();
        
        JComboBox day = (JComboBox)parent.getComponent(0);
        JComboBox month = (JComboBox)parent.getComponent(1);
        JComboBox year = (JComboBox)parent.getComponent(2);
        
        
        int dayInt = getSelectedInteger(day);
        int mmInt = getSelectedInteger(month);
        int yyInt = getSelectedInteger(year);
        
        if(problem == day){
            if(dayInt == 0) return;
            switch(dayInt){
                case 29:
                    if(mmInt == 2){
                        if(yyInt > 0 && !isLeapYear(yyInt)){
                            year.setSelectedIndex(0);
                        }
                    }
                    break;
                case 30:
                    if(isLongMonth(mmInt) && mmInt > 0 || mmInt == 2) month.setSelectedIndex(0);
                    break;
                case 31:
                    if(!isLongMonth(mmInt) && mmInt > 0 || mmInt == 2) month.setSelectedIndex(0);
                    break;
                default:
                    return;
            }
        }else if(problem == month){
            if(mmInt == 0) return;
            if(mmInt == 2){
                if(yyInt == 0) if(dayInt > 29) day.setSelectedIndex(0);
                if(isLeapYear(yyInt)){
                    if(dayInt > 29) day.setSelectedIndex(0);
                }else{
                    if(dayInt > 28) day.setSelectedIndex(0);
                }
            }else if(!isLongMonth(mmInt)){
                if(dayInt == 31) day.setSelectedIndex(0);
            }
        }else if(problem == year){
            if(yyInt ==0) return;
            if(mmInt == 2 && dayInt == 29){
                if(!isLeapYear(yyInt)) 
                    day.setSelectedIndex(0);
            }
        }
    }
        
   private boolean isLongMonth(int month){
       return (month == 1 || month ==3 || month == 5 || month == 7 || month ==8 || month ==10 || month ==12);
   }
    
   private int getSelectedInteger(JComboBox input){
       String result = (String)input.getSelectedItem();
       if(result.equals("DD")||result.equals("MM")||result.equals("YY")) return 0;
       return Integer.parseInt(result);
   }
   
   private boolean isLeapYear(int year){
       return (year%400 == 0) || ((year%100) != 0 && (year%4 == 0));
   }
}
